<template>
  <v-container fluid>
    <v-row justify="center">
      <v-col sm="4" md="4" lg="3">
        <v-card>
          <v-img src="../assets/login/background.png" class="white--text align-center" alt="昵称修改">
            <v-card-title>昵称修改</v-card-title>
          </v-img>
          <v-form ref="usernameForm" v-model="valid" lazy-validation>
            <v-card-text>
              <v-text-field v-model="user.username" :rules="[usernameRules.required, usernameRules.lengthLimit, usernameRules.isStrong, usernameRules.isRepeat(usernameError)]" label="用户名"></v-text-field>
              <!--保存按钮-->
              <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">保存</v-btn>
            </v-card-text>
          </v-form>
        </v-card>
      </v-col>
    </v-row>
    <v-snackbar
      v-model="snackbar"
    >
      用户名修改成功
      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          Close
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
export default {
  name: 'Username',
  data: () => ({
    snackbar: false,
    valid: true,
    user: {
      username: ''
    },
    usernameError: '',
    usernameRules: {
      required: v => !!v || '用户名不能为空',
      lengthLimit: v => (v.length >= 2 && v.length <= 20) || '用户名应该在2-20个字符之间',
      isStrong: v => !/\W+/.test(v) || '用户名只能包含字母、数字、下划线',
      isRepeat: (usernameError) => usernameError.length === 0 || usernameError
    }
  }),
  methods: {
    validate () {
      const valid = this.$refs.usernameForm.validate()
      if (valid) {
        this.$axios.patch('rest_auth/user/', {
          username: this.user.username
        }).then(response => {
          console.log(response)
          // 用户名修改成功后重新设置user
          this.$store.commit('setUser', response.data)
          // 弹出消息条提示成功修改
          this.snackbar = true
        }).catch(error => {
          console.log(error)
          // 注册不成功，说明用户名已被注册
          this.usernameError = '用户名已被注册'
          // 重新验证表单
          this.$refs.usernameForm.validate()
        })
      }
    }
  },
  created () {
    this.user.username = this.$store.state.user.username ? this.$store.state.user.username : ''
  },
  watch: {
    'user.username': function () {
      this.usernameError = ''
    }
  }
}
</script>

<style scoped>

</style>
